package com.dhgate.spu.analysis.collector;

import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.dhgate.spu.analysis.bean.ExtractKeyword;
import com.dhgate.spu.analysis.bean.Product;
import com.dhgate.spu.analysis.bean.SpuStandard;
import com.dhgate.spu.analysis.consts.CommonConsts;
import com.dhgate.spu.analysis.consts.SpuStandardConsts;
import com.dhgate.spu.analysis.util.CommonUtil;
import com.dhgate.spu.analysis.util.StringUtil;

/**
 * @author: wangguodong
 * @create: 2014-3-6 上午11:42:48
 * @description:
 */
public class StandardCollector implements ICollector {

	@Override
	public void process(Product p) {

		regulateProduct(p);
		List<SpuStandard> spuStandList = SpuStandardConsts.getSpuStandList(p
				.getProdLineId());
		if (spuStandList == null || spuStandList.size() == 0) {
			p.setExtField(CommonConsts.ExtFieldName.ERROR,
					CommonConsts.ErrorValue.NOT_HAVE_SPU_STANDARD);
			return;
		}

		for (SpuStandard spuStand : spuStandList) {// 遍历规则，优先匹配最前面的规则
			if (computeSpuUniqueKeyAndSpuStandardId(p, spuStand)) {
				break;
			}
		}

		if (StringUtil.isEmpty(p
				.getExtField(CommonConsts.ExtFieldName.SPU_STANDARD_ID))) {
			p.setExtField(CommonConsts.ExtFieldName.SPU_STANDARD_ID, "nohave");
		}

	}

	protected void regulateProduct(Product p) {
	};

	// attrId1:attrVal1,attrVal2;attrId2:attrVal1,attrVal2|extfiled1,extfiled2
	protected boolean computeSpuUniqueKeyAndSpuStandardId(Product p,
			SpuStandard spuStand) {
		
		StringBuffer spuAttrUniqueKeySB = new StringBuffer();
		StringBuffer spuExtUniqueKeySB = new StringBuffer();
		// 1. 判断是否有排他属性值规则(如果有，产品上有任何一个则返回false)
		if (spuStand.getAbandonMap() != null
				&& spuStand.getAbandonMap().size() > 0) {
			for (Long key : spuStand.getAbandonMap().keySet()) {
				for (Long valId : spuStand.getAbandonMap().get(key)) {
					if (p.getAttrValIdSet().contains(valId)) {
						return false;
					}
				}
			}
		}
		// 2. 判断是否有属性关键值规则(如果有，产品上没有任何一个则返回false)
		if (spuStand.getKeyMap() != null
				&& spuStand.getKeyMap().size() > 0) {
			for (Long key : spuStand.getKeyMap().keySet()) {
				for (Long valId : spuStand.getKeyMap().get(key)) {
					if (!p.getAttrValIdSet().contains(valId)) {
						return false;
					}
				}
			}
		}
		// 3. 判断是否有有效属性值（如果有,剔除无效属性值）
				if (spuStand.getValidMap() != null && spuStand.getValidMap().size() > 0) {
					for (Long key : spuStand.getValidMap().keySet()) {
						List<Long> attrValIdList = p.getAttrValIdList(key);
						if (attrValIdList != null && attrValIdList.size() > 0) {
							Set<Long> validSet = spuStand.getValidMap().get(key);
							List<Long> newValIdList = new ArrayList<Long>();
							for (Long valId : attrValIdList) {
								if (validSet.contains(valId)) {
									newValIdList.add(valId);
								}
							}
							p.setAttrValIdList(key, newValIdList);
						}
					}
				}
		if (spuStand.getAttrIdList() != null
				&& spuStand.getAttrIdList().size() > 0) {
			for (Long attrId : spuStand.getAttrIdList()) {
				List<Long> attrValIdList = p.getAttrValIdList(attrId);
				if (attrValIdList == null || attrValIdList.size() == 0) {
					return false;// 其中任何一个属性缺失，不能计算
				}
				spuAttrUniqueKeySB.append(attrId + ":");
				int size = attrValIdList.size();
				for (int i = 0; i < size; i++) {
					spuAttrUniqueKeySB.append(attrValIdList.get(i));
					if (i < size - 1) {
						spuAttrUniqueKeySB.append(",");
					}
				}
				spuAttrUniqueKeySB.append(";");
			}
		}

		if (spuStand.getExtFieldList() != null
				&& spuStand.getExtFieldList().size() > 0) {
			for (String extFieldName : spuStand.getExtFieldList()) {
				String fieldValue = p.getExtField(extFieldName);
				if (StringUtil.isEmpty(fieldValue)) {
					return false;// 其中任何一个提取field为空，不能计算
				}
				spuExtUniqueKeySB.append(fieldValue + ",");
			}
		}
		String spukeyword="";
        if(spuStand.getExtractKeyword()!=null&&spuStand.getExtractKeyword().isUsable()){
        	ExtractKeyword exk=spuStand.getExtractKeyword();
        	String content="";
        	boolean flag=false;
        	//循环抽取字段
        	for(String name:exk.getSourceFieldNames()){
        		if(name.equals("productname")){
        			content=p.getProductName();
        		}else if(name.equals("shortdescription")){
        			content=p.getShortDescription();
        		}else if(name.equals("keywords")){
        			content=p.getKeywords();
        		}
        		if(StringUtil.isEmpty(content)){
        			continue;
        		}
        		Set<String> contents=CommonUtil.getKeywordSet(content);
        		//循环关键字组，匹配成功退出
        		for(Set<String> keys:exk.getKeywordSet()){
        			if(contents.containsAll(keys)){
        				spukeyword+=keys;
        				flag=true;
        				break;
        			}
        		}
        		if(flag){
        			break;
        		}
        	}
        }
		if (spuAttrUniqueKeySB.length() == 0 && spuExtUniqueKeySB.length() == 0&&spukeyword.length()==0) {
			return false;
		}

		String spuUniqueKey = "";

		if (spuAttrUniqueKeySB.length() > 0) {
			spuUniqueKey = "attrs "
					+ spuAttrUniqueKeySB.substring(0, spuAttrUniqueKeySB
							.length() - 1);
		}

		if (spuExtUniqueKeySB.length() > 0) {// 注意|分割的时候要用"\\|"
			spuUniqueKey = spuUniqueKey
					+" |ExtFields "
					+ spuExtUniqueKeySB.substring(0,
							spuExtUniqueKeySB.length() - 1);
		}
		if(spukeyword.length()>0){
			spuUniqueKey = spuUniqueKey
			+" |keywords "+spukeyword;
		}
		p.setExtField(CommonConsts.ExtFieldName.SPU_STANDARD_ID, spuStand
				.getId());
		p.setExtField(CommonConsts.ExtFieldName.SPU_UNIQUE_KEY, spuUniqueKey);
		return true;
	}

	/**
	 * case1: Screen MTK6589 Quad Phone Android 4.2 Touch 3==>Touch 3 case2:
	 * Screen MTK6589 Quad Phone Android 4.2 ==>MTK6589
	 * 
	 * @param keywordList
	 *            : 按照keyword长度降序排好的list
	 * @param productName
	 *            : 转换为小写的要提取关键字的字符串
	 * @param pNameSet
	 *            : 字符串转换小写后用空格分隔组成的set
	 * @return String
	 */
	protected String xtractKeyword(List<String> keywordList,
			String productName, Set<String> pNameSet) {
		if (keywordList == null || keywordList.size() == 0) {
			return null;
		}
		productName = productName.toLowerCase();

		for (String keyword : keywordList) {
			if (!keyword.contains(" ")) {
				if (pNameSet.contains(keyword)) {
					return keyword;
				}
			} else if (productName.contains(keyword)) {
				return keyword;
			}
		}
		return null;
	}
	
	protected String xtractKeyword(List<String> keywordList, String str) {
		if (keywordList == null || keywordList.size() == 0) {
			return null;
		}
		str = str.toLowerCase();
	
		for (String keyword : keywordList) {
			if (!keyword.contains(" ")) {
				String partNameArray[] = str.split(" ");
				Set<String> partNameSet = new HashSet<String>();
				for (String partName : partNameArray) {
					partNameSet.add(partName.trim());
				}
				if (partNameSet.contains(keyword)) {
					return keyword;
				}
			} else if (str.contains(keyword)) {
				return keyword;
			}
		}
		return null;
	}

	@Override
	public void init() throws Exception {
	}

}
